<?php
/**
 * Manage public advertising
 * @author Tuong Tran <tuong.tran@outlook.com>
 */
class AdvertisingController extends Controller{
    public $layout = 'column2';

    public function actionIndex(){

    }

    /**
     * get all products in the category
     * @param string $alias category unique item
     */
    public function actionCategory($alias){
        //retreive category
        $category = Category::model()->findByAttributes(array(
            'alias' => $alias
        ));

        if(!$category){
            throw new CHttpException(404, 'Page was not exists!');
        }

        //public the meta keywords, meta title, and meta desciption
        $cs = cs();
        $cs->registerMetaTag($category->meta_description, 'description');
        $cs->registerMetaTag($category->meta_keywords, 'keywords');
        if($category->meta_title != ''){
            $this->pageTitle = $category->meta_title;
        }else{
            $this->pageTitle = $category->name;
        }

        //find all products in the categories
        $criteria = new CDbCriteria();
        $criteria->addCondition('t.category_id='.$category->category_id);
        $criteria->order = 't.updated DESC';
        //pagination
        $pages = new CPagination();
        $pages->setItemCount(Advertising::model()->count($criteria));
        $pages->setPageSize(param('pageSize'));

        //retreived search results
        $models = Advertising::model()->with('category')->findAll($criteria);

        $this->render('category', array(
            'models' => $models,
            'pages' => $pages
        ));
    }

    /**
     * view advertising detail
     * @param int $id adv id
     * @param string $name name for SEO
     */
    public function actionView($id, $name = ''){
        //find model
        $model = Advertising::model()->with('category', 'type')->findByPk($id);

        if(!$model){
            throw new CHttpException(404, 'Page was not exists!');
        }

        //public page title
        $cs = cs();
        $cs->registerMetaTag(h($model->title, 60), 'description');
        $cs->registerMetaTag(h($model->description, 160), 'keywords');

        $this->render('view', array(
            'model' => $model
        ));
    }


    /**
     * register an ads
     */
    public function actionCreate(){
        $model = new Advertising;
        //set default exp date and dedault name
        if(!user()->isGuest){
            $user = user()->getModel();
            $model->author = $user->display_name;
            $model->email = $user->email;
            $model->country = $user->country_iso;
            $model->state = $user->state;
            $model->city = $user->city;
        }

        // Uncomment the following line if AJAX validation is needed
        $this->performAjaxValidation($model);
        if (isset($_POST['Advertising'])) {
            $model->attributes = $_POST['Advertising'];

            //default public is public>?
            $model->status = Advertising::STATUS_PUBLISHED;

            //reset price
            if(!$_POST['priceType']){
                $model->price = NULL;
            }

            //update expired time
            switch ($_POST['duration']){
                case '1M':
                    $model->expired = time() + 30 * 24 * 60 * 60;
                    break;
                case '2W' :
                    $model->expired = time() + 14 * 24 * 60 * 60;
                    break;
                default:
                    $model->expired = time() + 7 * 24 * 60 * 60;
                    break;
            }

            //save new image
            if(($newImage = CUploadedFile::getInstanceByName('image'))){
                //save new image
                $newFileName = uniqid().'.'.$newImage->getExtensionName();
                if($newImage->saveAs(UPLOAD_PATH . $newFileName)){
                    $model->image = $newFileName;
                }
            }

            if ($model->save()){
                user()->setFlash('success', 'Add new adv successfully.');

                $this->redirect($model->getUrl());
            }
        }

        $this->render('create', array(
            'model' => $model,
        ));
    }



    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model) {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'advertising-form') {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }
}